import { config } from '../config.js'

const tips = {
    1: '抱歉，出现了一个错误',
    1005:'appkey无效，请前往www.7yue.pro申请',
    3000:'期刊不存在'
}
// 改写http为promise
class HTTP{
    request({url,method='GET',data={}}){
        return new Promise((reslove, reject) => {
            this._request(url,reslove, reject, method, data)
        })
    }
    _request(url, reslove, reject, method="GET", data={}){
        wx.request({
            url: config.base_url + url,
            method:method,
            data:data,
            header: {
                'content-type': 'application/json',
                'appkey': config.appkey
            },
            success: res => {
                // 处理请求成功
                let code = res.statusCode.toString()
                if(code.startsWith('2')){
                    reslove(res.data)
                }else{
                    reject()
                    this._show_error(res.data.error_code)
                }
            },
            fail: err => {
                reject()
                this._show_error(1)
            }
        })
    }
    _show_error(error_code){
        const tip = tips[error_code]
        wx.showToast({
            title: tip?tip:tips[1],
            icon:'none',
            duration:2000
        })
    }
}

export { HTTP }